package com.yakami.ocean.view.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.annimon.stream.Stream;
import com.trello.rxlifecycle.ActivityEvent;
import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.bean.TestItem;
import com.yakami.ocean.bean.TestPaper;
import com.yakami.ocean.event.Event;
import com.yakami.ocean.event.RxBus;
import com.yakami.ocean.view.activity.base.BaseHoldBackTabsActivity;
import com.yakami.ocean.view.fragment.TestFragment;
import com.yakami.ocean.view.fragment.TestResultFragment;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Yakami, Created on 2016/4/21
 */
public class TestActivity extends BaseHoldBackTabsActivity {

    private int testId;
    private int mCurrentItem = 0;
    private TestPaper mTestPaper;
    private List<TestItem> mAnswer = new ArrayList<>();

    private double mScore = 0;
    private int mRightTime = 0;
    private int mWrongTime = 0;
    private double mAccuracy = 0;

    @Override
    public void onCreate(Bundle savedInstanceBundle) {
        super.onCreate(savedInstanceBundle);

        testId = getIntentHelper().getInt("id", 1);
        mTitle.setText(getIntentHelper().getString("name"));
        initTabs(savedInstanceBundle != null);
    }

    @Override
    public void initTabs(boolean isRestarted) {
        super.initTabs(isRestarted);

        ServerAPI.getOceanAPI()
                .getTestPaper(testId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(testPaper -> {
                    mTestPaper = testPaper;
                    setTestItem(mCurrentItem);
                    RxBus.with(this)
                            .setEvent(Event.EventType.NEXT_PROBLEM)
                            .setEndEvent(ActivityEvent.DESTROY)
                            .onNext(event -> {
                                mAnswer.add(event.getMessage());
                                setTestItem(++mCurrentItem);
                            }).create();
                }, throwable -> {
                    throwable.printStackTrace();
                    toast(mRes.getString(R.string.network_error));
                });
    }

    private void setTestItem(int pos) {
        if (mTestPaper.list.size() > pos) {
            TestFragment fragment = new TestFragment();
            TestItem item = mTestPaper.list.get(mCurrentItem);
            item.title = (mCurrentItem + 1) + ". " + item.title;
            fragment.setTestItem(item);
            getSlideAnimTransaction().replace(R.id.view_content, fragment, "ITEM_" + mCurrentItem).commit();
        } else {
            showResult();
        }
    }

    private void showResult() {
        Stream.of(mAnswer)
                .forEach((item) -> {
                    if (item.selected == item.answer)
                        mRightTime++;
                    else
                        mWrongTime++;
                });
        mScore = (100.0 / mAnswer.size()) * mRightTime;
        mAccuracy = mRightTime / ((float) mAnswer.size());
        TestResultFragment fragment = new TestResultFragment();
        fragment.setData((double) Math.round(mScore * 100) / 100 + "", mRightTime + "道", mWrongTime + "道", (double) Math.round(mAccuracy * 100) + "%");
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_out_left);
        transaction.replace(R.id.view_content, fragment, "TEST_RESULT").commit();

        //发送成绩
        ServerAPI.getOceanAPI()
                .setTestRecord((int) mScore, testId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {

                }, Throwable::printStackTrace);
    }

    @Override
    public int onBindLayout() {
        return R.layout.activity_test;
    }
}
